/**
 * Created by zlj on 2016/12/8.
 */
var $ = require('jquery');
require('easyui');
var $alert = require("libs/alert");
var $confirm = require("libs/confirm");
var $validate = require("js-path/OneErrorPlaceFormValidate");
require('fancybox');
var similarGoodsCopyReq = null;
var isSale = require('libs/user-type').isSale;
$(function () {
    $(window).resize(function () {
        var $this = $(this);
        $('#goods_check_table').datagrid("resize",{
            width: 'auto',
            height: $this.height()
        });
    });
    $validate.validator(
        {form:"#check-sumbit",button:"#checkSubmit"},
        {
        declareName:{required:function (element) {
            return $('#check-sumbit input[name=checkReult]:checked').val() == 'Y';
        }},
        importGoodsTax:{number:true},
        exportGoodsTax:{number:true},
        hsCode:{required:function (element) {
            return $('#check-sumbit input[name=checkReult]:checked').val() == 'Y';
        },digits:true}},
        {
            declareName:{required:'请按要求填写'},
            importGoodsTax:{number:'请按要求填写'},
            exportGoodsTax:{number:'请按要求填写'},
            hsCode:{required:'请按要求填写',digits:'请按要求填写'}
            },
        function () {
            var data = $('#check-sumbit').serializeObject();
            return data;
        },
        function (result) {
            if(result.code =='200'){
                $("#goodsinfo").modal("hide");
                $("#goodsdetail").modal("hide");
                $("#goods_check_table").datagrid("reload");
            }else{
                $alert(result.message);
            }
        }
    );
    /**
     * 相似商品copy
     */
    $(document).on('click','a[name=copy]',function () {
        var rowsData =  $('#similarGoodsTable').datagrid('getRows');
        var row = rowsData[$(this).data('index')];
        $("#check-sumbit input[name=importGoodsTax]").val(row.importGoodsTax);
        $("#check-sumbit input[name=hsCode]").val(row.hsCode);
        $("#check-sumbit input[name=exportGoodsTax]").val(row.exportGoodsTax);
        $("#check-sumbit input[name=declareName]").val(row.declareName);
        $.fancybox.close();
    });
    $('#goodsinfo').on('hidden.bs.modal',function () {
        similarGoodsCopyReq = null;
        $('#myModalLabel').empty();
        $('#id').val('');
        $('#importId').val('');
        $('#goodsinfo .big-img img').attr('src','');
        $('#goodsinfo .min-img').empty();
        var $spans = $('#goodsinfo .iteam span');
        $spans.empty();
        $("#check-sumbit textarea").empty();
        $("#check-sumbit input[type=text]").val('');
        $("#check-sumbit input[name='checkReult']").get(0).checked=true;
        $('#areatext').hide();
    });
    $("#goodsdetail").on("hidden.bs.modal",function () {
        $('#myModalLabel1').empty();
        $('#goodsdetail .big-img img').attr('src','');
        $('#goodsdetail .min-img').empty();
        var $spans = $('#goodsdetail .iteam span');
        $spans.empty();
        $("#check-sumbit2 textarea").empty();
        $("#check-sumbit2 input[type=text]").val('');
        $("#check-sumbit2 input[name='checkReult']").get(0).checked=true;
        $('#areatext2').hide();
    });
    $('#checkInfoCopyButton').on('click',function () {
        $.ajax({
            url:'api/v1/p/mms/goods/check/copyList',
            type:'get',
            data:similarGoodsCopyReq
        })
        .done(function (res) {
            if(res.code == 200){
               var rows = res.data.rows;
                if(rows == undefined||rows.length == 0){
                    alert('没有相似商品信息');
                }else if(rows.length == 1){
                    $("#check-sumbit input[name=importGoodsTax]").val(rows[0].importGoodsTax);
                    $("#check-sumbit input[name=hsCode]").val(rows[0].hsCode);
                    $("#check-sumbit input[name=exportGoodsTax]").val(rows[0].exportGoodsTax);
                    $("#check-sumbit input[name=declareName]").val(rows[0].declareName);
                }else{
                    $.fancybox.open({
                        type : 'inline',
                        src  : '#similarGoodsWrap',
                        transitionEffect  : "fade",
                        beforeShow: function () {
                            $('#similarGoodsTable').datagrid({
                                url:'api/v1/p/mms/goods/check/copyList',
                                border : false,
                                pagination : true,
                                pageSize : 10,
                                pageList : [ 10, 20,  50 ],
                                emptyMsg : "暂无数据",
                                rownumbers:true,
                                queryParams: similarGoodsCopyReq,
                                columns:[[
                                    {
                                        field:'code',
                                        title:'商品编码',
                                        width: 75,
                                        formatter:function (value,row,index) {
                                            return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                                        }
                                    },{
                                        field:'chName',
                                        title:'中文名称',
                                        width: 75,
                                        formatter:function (value,row,index) {
                                            return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                                        }
                                    },
                                    {
                                        field:'hsCode',
                                        title:'海关H.S.编码',
                                        width: 88,
                                        formatter:function (value,row,index) {
                                            return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                                        }
                                    },{
                                        field:'importGoodsTax',
                                        title:'进口国税率',
                                        formatter:function (value,row,index) {
                                            if(value){
                                                return value+'%';
                                            }
                                            return '';
                                        }
                                    },{
                                        field:'exportGoodsTax',
                                        title:'出口国退税率',
                                        formatter:function (value,row,index) {
                                            if(value){
                                                return value+'%';
                                            }
                                            return '';
                                        }
                                    },{
                                        field:'declareName',
                                        title:'申报品名',
                                        width: 75,
                                        formatter:function (value,row,index) {
                                            return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                                        }
                                    },{
                                        field:'lastUpdateDt',
                                        title:'审核日期'
                                    },{
                                        field:'opt',
                                        title:'操作',
                                        formatter:function (value,row,index) {
                                            return "<a href='javascript:;' name='copy' data-index='"+index+"'>复制审核</a>";
                                        }
                                    }
                                ]],
                                loadFilter:function(data){
                                    if(data.code!='200'){
                                        $alert(data.message);
                                    }
                                    return data.data;
                                }
                            });
                        }
                    });
                }
            }else{
                alert(res.message);
            }
        });
    });
    tableInt();
    comboxInit('api/v1/p/mms/area/query',{'level':'1'}
        ,$("#importCountryId"));
    $('#tb a[name=search]').on('click',function () {
        $('#goods_check_table').datagrid('load',{
            hasBattery:$('#tb input[name=hasBattery]').val(),
            entId:$('#tb input[name=entId]').val(),
            code:$('#tb input[name=code]').val(),
            chName:$('#tb input[name=chName]').val(),
            auditSts:$('#tb input[name=auditSts]').val(),
            importCountryId:$('#tb input[name=importCountryId]').val()
        })
    });

    $('#checkGoods').on('click',function () {
        var rows = $("#goods_check_table").datagrid("getSelections");
        if(rows.length == 0){
            $alert('请至少选择一个商品进行审核');
        }else{
            var data = {};
            data["isNew"] = 'N';
            var ids = [];
            console.log(rows.length)
            for (var i = 0 ;i<rows.length ;i++){
                if(rows[i].auditSts != 'P'){
                    var id = {};
                    id["id"] = rows[i].id;
                    id["importId"] = rows[i].importId;
                    ids.push(id);
                }
            }
            if(ids==null||ids==''){
                $alert('所选的商品已经审核完成!');
                return false;
            }
            data["goodsLoadPos"] = ids;
            opt('api/v1/p/mms/goods/check/checkGoods',data,function (result) {
                $alert(result.message);
                $("#goods_check_table").datagrid("reload");
            })
        }
    });

    $('body').on('click','a[name=audi]',function () {
        var rowsData =  $('#goods_check_table').datagrid('getRows');
        var row = rowsData[$(this).attr('row')];
        loadGoods(row.id,row.importId);
    });
    //test
    $('body').on('click','a[name=detailaudi]',function () {
        var rowsData =  $('#goods_check_table').datagrid('getRows');
        var row = rowsData[$(this).attr('row')];
        goodsDetail(row.id,row.importId);
    });
    $('#checkSubmit').on('click',function () {
        // $('#check-sumbit').attr('action','api/v1/p/mms/goods/check/checkGood');
        if($('#check-sumbit input[name=checkReult]:checked').val() == 'N' && $('#areatext').val() == ''){
            $alert('审核失败原因不能为空!');
            return;
        } else {
            $('#check-sumbit').submit();
        }
    });
    $("#check-sumbit input[name=checkReult]").on("change",function () {
        if(this.value =='Y'){
            $('#areatext').hide();
        }else{
            $('#areatext').show();
        }
    });
    function tableInt() {
        $('#goods_check_table').datagrid({
            url:'api/v1/p/mms/goods/check/list?type=N',
            border : false,
            height:$(window).height(),
            pagination : true,
            idField : 'id',
            pageSize : 20,
            pageList : [ 20, 50,  100 ],
            checkOnSelect : false,//单击选中
            emptyMsg : "暂无数据",
            selectOnCheck : true,
            rownumbers:true,
            frozenColumns:[[{
                field : 'id',
                checkbox:true
            }]],
            columns:[[
                {
                    field:'entName',
                    title:'客户名称',
                    width:fixWidth(0.15),
                    sortable:true,
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'code',
                    title:'商品编码',
                    width:fixWidth(0.12),
                    sortable:true,
                    formatter:function (value,row,index) {
                        return "<a href='javascript:;' class='ellipsis' name='detailaudi' row='"+index+"'>"+value+"</a>";
                    }
                },
                {
                    field:'chName',
                    title:'商品中文名称',
                    sortable:true,
                    width:fixWidth(0.11),
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'hasBattery',
                    title:'是否带电',
                    width:fixWidth(0.07),
                    sortable:true,
                    formatter:function (value,row,index) {
                        return 'Y'==value?'是':'否';
                    }
                },{
                    field:'importCountryName',
                    title:'进口国',
                    width:fixWidth(0.08),
                    sortable:true,
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'detailWebsite',
                    title:'网址',
                    width:fixWidth(0.18),
                    sortable:true,
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'lastUpdateDt',
                    title:'提交时间',
                    width:fixWidth(0.1),
                    sortable:true,
                    formatter:function (value,row,index) {
                        return "<div class='ellipsis' title='"+value+"'>"+value+"</div>";
                    }
                },{
                    field:'auditSts',
                    title:'审核状态',
                    width:fixWidth(0.07),
                    sortable:true,
                    formatter:function (value,row,index) {
                        if(value == 'C'){
                            return '已提交';
                        }else if(value=='P'){
                            return '审核通过';
                        }else if(value == 'R'){
                            return '审核失败';
                        }
                    }
                },{
                    field:'importId',
                    hidden:true
                },{
                    field:'opt',
                    title:'操作',
                    hidden:isSale,
                    width:fixWidth(0.07),
                    formatter:function (value,row,index) {
                        switch (row.auditSts){
                            case 'C':
                                return '<a href="javascript:;" name="audi" row="'+index+'"><i class="glyphicon glyphicon-pencil"></i>审核</a>';
                            default : return '';
                        }
                    }
                }
            ]],
            loadFilter:function(data){
                if(data.code!='200'){
                    $alert(data.message);
                    return data.data;
                }
                return data.data;
            },
            onClickRow:function (index,data) {
                var $row = $("#datagrid-row-r1-1-"+index).find("input[type=checkbox]");
                if(!$row.prop("checked")){
                    $(this).datagrid('unselectRow', index);
                }else{
                    $(this).datagrid('selectRow', index);
                }
            },
            toolbar:"#tb"
        });
        $("#ft").show();
    }
    function fixWidth(percent)
    {
        return (document.body.clientWidth - 5) * percent ;
    }
//opt 操作 callback回调函数
    function opt(url,data,callback) {
        $.ajax({
            url:url,
            type:'post',
            contentType: "application/json; charset=utf-8",
            data:JSON.stringify(data),
            dataType:'json',
            success:function (result) {
                callback(result);
            },
            error:function (e) {
                console.error('接口：'+url+'获取失败');
            }
        })
    }
//load goods
    function loadGoods(id,importId) {
        $.ajax({
            url:'api/v1/p/mms/goods/check/load',
            type:'post',
            data:{
                id:id,
                importId:importId
            },
            dataType:'json',
            success:function (result) {
                if(result.code == 200){
                    appendData(result.data);
                    $('#goodsinfo').modal('show');
                }else{
                    $alert(result.message);
                }
            },
            error:function (e) {
                console.error('url: api/v1/p/mms/goods/check/load 接口失败');
            }
        })
    }
//goods detail
    function goodsDetail(id,importId) {
        $.ajax({
            url:'api/v1/p/mms/goods/check/load',
            type:'post',
            data:{
                id:id,
                importId:importId
            },
            dataType:'json',
            success:function (result) {
                if(result.code == 200){
                    goodsData(result.data);
                    $('#goodsdetail').modal('show');
                }else{
                    $alert(result.message);
                }
            },
            error:function (e) {
                console.error('url: api/v1/p/mms/goods/check/load 接口失败');
            }
        })
    }
//append data
    function appendData(data) {
        $('#myModalLabel').html(data.chName);
        $('#id').val(data.id);
        $('#importId').val(data.importId);
        var spans = '';
        $.each(data.pics,function (index,obj) {
            if(index == 0){
                $('#goodsinfo div.big-img img').attr('src',obj.filePath);
            }else{
                spans +="<span><img src='"+obj.filePath+"'></span>";
            }
        })
        $('#goodsinfo div.min-img').append(spans);
        var $spans = $('#goodsinfo div.iteam span');
        $($spans[0]).html(data.chName);
        $($spans[1]).html(data.enName);
        $($spans[2]).html(data.code);
        $($spans[3]).html(data.spec);
        $($spans[4]).html(data.model);
        $($spans[5]).html(data.brand);

        var batteryType='';
        if(data.batteryType == 'alkaline'){
            batteryType = '碱性电池';
        } if(data.batteryType == 'lithium'){
            batteryType = '锂电池';
        }else{
            batteryType = '不带电';
        }
        $($spans[6]).html(batteryType);

        var keywords ;
        if(data.keyword.length > 0){
            keywords = data.keyword.join(',');
        }else {
            keywords = '';
        }
        $($spans[7]).html(keywords);

        $($spans[8]).html(data.regGrossWeight);
        $($spans[9]).html(data.regLength);
        $($spans[10]).html(data.regWidth);
        $($spans[11]).html(data.regHeight);

        $($spans[12]).html(data.hsCode);
        $($spans[13]).html(data.manageType);
        $($spans[14]).html(data.exportGoodsTax);

        $($spans[15]).html(data.importCountry);
        $($spans[16]).html(data.declaredPrice);
        $($spans[17]).html(data.importGoodsPrice);
        $($spans[18]).html(data.currency);

        $($spans[19]).html(data.deliveryCycle);
        $($spans[20]).html(data.detailWebsite);
        $($spans[20]).parent('a').attr('href',data.detailWebsite);
        similarGoodsCopyReq = {
            entId : data.entId,
            detailWebsite: data.detailWebsite
        };
        $($spans[21]).html(data.summary);

        $('#areatext').html(data.orderRejectReason);
        if(data.auditSts == 'R'){
            $("#check-sumbit input[name='checkReult']").get(1).checked=true;
            $('#areatext').show();
        }else if(data.auditSts == 'P'|| data.auditSts == 'C'){
            $("#check-sumbit input[name='checkReult']").get(0).checked=true;
            $('#areatext').hide();
        }
        //2017-3-10
        $("#check-sumbit input[name=importCountry]").val(data.importCountry);
        $("#check-sumbit input[name=importGoodsTax]").val(data.importGoodsTax);
        $("#check-sumbit input[name=hsCode]").val(data.hsCode);
        $("#check-sumbit input[name=exportGoodsTax]").val(data.exportGoodsTax);
        $("#check-sumbit input[name=declareName]").val(data.declareName );
        $("#check-sumbit input[name=declareFactor]").val(data.declareFactor );
    }

//detail data
    function goodsData(data) {
        $('#myModalLabel1').html(data.chName);
        var spans = '';
        $.each(data.pics,function (index,obj) {
            if(index == 0){
                $('#goodsdetail div.big-img img').attr('src',obj.filePath);
            }else{
                spans +="<span><img src='"+obj.filePath+"'></span>";
            }
        })
        $('#goodsdetail div.min-img').append(spans);
        var $spans = $('#goodsdetail div.iteam span');
        $($spans[0]).html(data.chName);
        $($spans[1]).html(data.enName);
        $($spans[2]).html(data.code);
        $($spans[3]).html(data.spec);
        $($spans[4]).html(data.model);
        $($spans[5]).html(data.brand);

        var batteryType='';
        if(data.batteryType == 'alkaline'){
            batteryType = '碱性电池';
        } if(data.batteryType == 'lithium'){
            batteryType = '锂电池';
        }else{
            batteryType = '不带电';
        }
        $($spans[6]).html(batteryType);

        var keywords ;
        if(data.keyword.length > 0){
            keywords = data.keyword.join(',');
        }else {
            keywords = '';
        }
        $($spans[7]).html(keywords);

        $($spans[8]).html(data.regGrossWeight);
        $($spans[9]).html(data.regLength);
        $($spans[10]).html(data.regWidth);
        $($spans[11]).html(data.regHeight);

        $($spans[12]).html(data.hsCode);
        $($spans[13]).html(data.manageType);
        $($spans[14]).html(data.exportGoodsTax);

        $($spans[15]).html(data.importCountry);
        $($spans[16]).html(data.declaredPrice);
        $($spans[17]).html(data.importGoodsPrice);
        $($spans[18]).html(data.currency);

        $($spans[19]).html(data.deliveryCycle);
        $($spans[20]).html(data.detailWebsite);
        $($spans[20]).parent('a').attr('href',data.detailWebsite);
        $($spans[21]).html(data.summary);

        $('#areatext2').html(data.orderRejectReason);
        if(data.auditSts == 'R'){
            $("#check-sumbit2 input[name='checkReult']").get(1).checked=true;
            $('#areatext2').show();
        }else if(data.auditSts == 'P'){
            $("#check-sumbit2 input[name='checkReult']").get(0).checked=true;
            $('#areatext2').hide();
        }
        //2017-3-10
        $("#check-sumbit2 input[name=importCountry]").val(data.importCountry);
        $("#check-sumbit2 input[name=importGoodsTax]").val(data.importGoodsTax);
        $("#check-sumbit2 input[name=exportGoodsTax]").val(data.exportGoodsTax);
        $("#check-sumbit2 input[name=hsCode]").val(data.hsCode);
        $("#check-sumbit2 input[name=declareName]").val(data.declareName );
        $("#check-sumbit2 input[name=declareFactor]").val(data.declareFactor );
    }

//添加参数
    function comboxInit(url,data,$select) {
        $select.combobox({
            url:url,
            valueField:'id',
            textField:'name',
            queryParams:data,
            loadFilter:function(result){
                if(result.code=='200'){
                    result.data.unshift({id:'',name:'全部'});
                    return result.data;
                }
            }
        })
    }

});

